local Msg = require("core.Msg")
local ExcelMap = require("excel.Map")
local Map = require("core.Map")
local Status = require("scene.Status")
local ObjHuman = require("core.ObjHuman")
local ObjPet = require("core.ObjPet")
local Obj = require("core.Obj")
local PetLogic = require("pet.PetLogic")

function send_err(human, err, arg1, arg2, arg3)
  if arg1 then
    err = string.format(err, arg1, arg2, arg3)
  end
  local mm = Msg.gc.GC_PET_ERR
  mm.err = err
  Msg.send(mm, human.fd)
end

function CG_PET_COMBAT(human, id)
  if human.db.hp < 0 then
      return
  end
  local cf = ExcelMap.scene[Map.scene_id_to_map_id[human.scene_id]]
  if cf.can_use_pet == 0 then
--    return send_err(human, Lang.PET_ERR_IN_MAP)
  end
  if human.status == Status.HUMAN_STATUS_OBSERVER then
--    return send_err(human, Lang.PET_ERR_PET_IN_OBSERVER)
  end
  local id = id
  if id == 0 then
    local maxx = 0
    for i = 0, human.db.petLen -1 do
      local next_create_time = human.db.pet[i].next_create_time
      if next_create_time >0  and maxx < next_create_time then
        maxx = next_create_time
        id = human.db.pet[i].id
      end
    end
    if id == 0 then
      id = 1
--      return send_err(human, Lang.PET_ERR_PET_NOT_EXIST)
    end
  end
  local pet = ObjHuman.getPet(human, id)
  if not pet then
--    return send_err(human, Lang.PET_ERR_PET_NOT_EXIST)
  end 
  local fight_pet = human.fight_pet_id and Obj.getObj(human.fight_pet_id, human.fight_pet_uid)
  if fight_pet and fight_pet.db.id ~= id then
      ObjPet.backPet(human)
  end
  human.db.petCombatId = id
  ObjPet.callPet(human, id)  
  ObjHuman.doCalc(human)
end

function CG_PET_CALLBACK(human)
  ObjPet.backPet(human)
end

--激活神将
function CG_PET_JIHUO(human, msg)
  PetLogic.jihuo(human, msg.id)
end
--神将升星
function CG_PET_STAR_UP(human, msg)
  PetLogic.starUp(human, msg.id)
end
--神将升阶
function CG_PET_STAGE_UP(human, msg)
  PetLogic.stageUp(human, msg.id)
end
--神将培养
function CG_PET_FEED(human, msg)
  PetLogic.petFeed(human, msg.id, msg.type)
end
--神将状态改变，
function CG_PET_STATUS_CHANGE(human, msg)
  PetLogic.statusChange(human, msg.id)
end
--神将装备合成
function CG_PET_EQUIP_HECHENG(human, msg)
  PetLogic.equipHecheng(human, msg.id, msg.equipIndex)
end
--查看神将装备合成所需道具
function CG_CHECK_PET_EQUIP(human, msg)
  PetLogic.checkEquip(human, msg.id)
end
--神将阁升级
function CG_PET_ATTIC_LV_UP(human)
  PetLogic.atticLvUp(human)
end

function CG_PET_LV_UP(human, msg)
  PetLogic.addExpItem(human, msg.id, msg.itemId, msg.cnt)
end
